/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div>
        <sf-textfield
            ref="textfield"
            v-model="password"
            class="password_item"
            :class="pwdItemCls"
            :default-width="defaultWidth"
            :default-disabled="defaultDisabled"
            :trigger-type="passwordStatus"
            :validator="_pswValidator"
            :allow-blank="isEdit"
            :field-title="fieldTitle"
            :type="inputType"
            :default-readonly="!editable"
            :placeholder="!editable ? '': undefined"
            @trigger="_onTrigger"
            v-on="$listeners" />
        <i
            :class="inputIcon(hidden)"
            class="sf-comp-iconfont"
            @mousedown="iconShow"></i>
    </div>
</template>

<script>
import { trim } from 'src/util/format';

/**
     * 1. 最短6位，最长64位 {6,64}
     * 2. 可以包含所有英文半角模式下可输入的所有字符（ASCII可显示字符 \x20-\x7E）
     *    oyhq(欧阳海清) 14:08:57
     *    密码的合法字符范围是英文半角模式下可输入的所有字符
     *    Array.from({length: '\x7e'.charCodeAt(0)-'\x20'.charCodeAt(0)}).map((v,index) => String.fromCharCode(index + '\x20'.charCodeAt(0))).join('')
     *    > !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}
     */
// const PWD_REGEX = /^[\x20-\x7E]+$/;

/**
         *
         * 默认的校验器
         * @param {string} pwd
         * @return {boolean | string}
         * @constructor
         */
function DEFAULT_VALIDATOR () {

    // 默认按照上方规定的表达式进行检测
    // if (!PWD_REGEX.test(pwd)) {
    //     return _('包含非法字符，只能英文半角模式下的字符');
    // }

    return true;
}

const PSW_MIN_LEN = 8;
const PSW_MAX_LEN = 32;


export default {
    props: {
        value: String,
        defaultWidth: Number,

        minLength: {
            type: Number,
            default: PSW_MIN_LEN
        },

        maxLength: {
            type: Number,
            default: PSW_MAX_LEN
        },
        defaultDisabled: Boolean,
        editable: Boolean,
        validator: {
            type: Function,
            default: DEFAULT_VALIDATOR
        },

        // 是否有显示密码明文功能
        canShowPsw: {
            type: Boolean,
            default: false
        },

        // 编辑状态情况下，可能为空
        isEdit: {
            type: Boolean,
            default: false
        }
    },

    data () {
        return {
            password: this.value,
            hidden: false
        };
    },

    watch: {
        value (newValue) {
            this.password = newValue;
        },

        password (newValue, oldValue) {
            if (newValue !== oldValue) {
                this.$emit('input', newValue);
            }
        }
    },

    computed: {
        display () {
            let length = this.password ? this.password.length : 0;
            return this.hidden ? ''.padStart(length, '*') : this.password;
        },

        passwordStatus () {
            return this.hidden ? 'eye-slash' : 'eye';
        },

        inputType () {
            return this.hidden ? 'text' : 'password';
        },

        fieldTitle () {

            // 走 sf-vue-component\src\widgets\form\form.vue @_getFieldLabel 抄的覆盖实现
            let fieldLabel = '';
            let fieldParent = this.$parent;
            fieldParent.$children.every((comp) => {

                // TODO: 如何合理的判断类型 SfFieldlabel
                if (comp && comp.$el && comp.$el.tagName === 'LABEL') {

                    // 直接拿文本，不支持html
                    fieldLabel = comp.$el.innerText || comp.$el.textContent;

                    // 删除原有的分隔符
                    if (fieldLabel && comp.separator) {
                        if (fieldLabel.slice(-1 * comp.separator.length) === comp.separator) {
                            fieldLabel = fieldLabel.slice(0, -1 * comp.separator.length);
                        }
                    }
                    return false;
                }
                return true;
            });
            fieldLabel = trim(fieldLabel);
            return fieldLabel || '';
        },

        pswMinLength () {
            return this.validator ? this.minLength : 0;
        },

        pswMaxLength () {
            return this.validator ? this.maxLength : PSW_MAX_LEN;
        },

        pwdItemCls () {
            return {
                'disabled-show-password': !this.canShowPsw,
                'password-readonly': !this.editable
            };
        }
    },

    methods: {
        inputIcon (showInput = false) {
            return showInput ? 'icon-comp-display' : 'icon-comp-hide';
        },
        iconShow () {
            let vm = this;
            vm.hidden = !vm.hidden;
        },

        _onTrigger () {
            let vm = this;
            vm.hidden = !vm.hidden;
        },

        _pswValidator (v) {
            let vm = this;
            if (vm.validator && typeof vm.validator === 'function') {

                // 为自定义函数则需要执行
                return vm.validator(v, DEFAULT_VALIDATOR);
            }

            return true;
        },

        validate () {
            return this.$refs.textfield.validate();
        }
    }
};
</script>

<style lang="stylus">
.password_item
    input
        padding-right 30px
    span
        display inline-block
    .psw
        width calc(100% - 2em)
        overflow hidden
        text-overflow ellipsis
        white-space nowrap
    i
        float right
        cursor pointer
    .eye-slash:before
        content '\f070'
        font-family 'FontAwesome'
    .eye:before
        content '\f06e'
        font-family 'FontAwesome'
    &.disabled-show-password
        button
            display none
    &.password-readonly
        input
            border none
        .sfv-textfield_input:active, .sfv-textfield_input:focus, .sfv-textfield_input
            background transparent
            padding-left 0
</style>
